import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import 'package:miuu_note_app/dao/diary_dao.dart';
import 'package:miuu_note_app/model/diary_entity.dart';
import 'package:miuu_note_app/page/diary_add_update.dart';
import 'package:table_calendar/table_calendar.dart';

import 'diary_detail.dart';

class DiaryPage extends StatefulWidget {
  const DiaryPage({super.key});

  @override
  State<DiaryPage> createState() => _DiaryPageState();
}

class _DiaryPageState extends State<DiaryPage> {
  CalendarFormat _calendarFormat = CalendarFormat.month;
  DateTime _focusedDay = DateTime.now().toUtc();
  DateTime _pageChangeDay = DateTime.now();
  String _yearMonth = '';
  late DateTime _selectedDay;
  // late List<String> _selectedEvents;
  List<DiaryModel> _pageChangeEvents = [];
  static const List<Locale> supportedLocales = <Locale>[
    Locale('en'),
    Locale('ja')
  ];

  void _getEventsForMonth(ts) async {
    DiaryListEntity? entity =
        await DiaryListDao.fetch(ts, 'getDiaryListByMonth');
    setState(() {
      _pageChangeEvents = entity!.diarys;
      _yearMonth = DateFormat('yyyy年MM月').format(ts);
      print(_yearMonth);
    });
  }

  void _getEventsForDate(ts) async {
    DiaryListEntity? entity =
        await DiaryListDao.fetch(ts, 'getDiaryListByDate');
    setState(() {
      _pageChangeEvents = entity!.diarys;
      _yearMonth = DateFormat('yyyy年MM月').format(ts);
      print(_yearMonth);
    });
  }

  @override
  void initState() {
    super.initState();
    print(_focusedDay);
    _selectedDay = _focusedDay;
    // _selectedEvents = _getEventsForDay(_selectedDay);
    _getEventsForDate(_pageChangeDay);
    // _getDairyList();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        supportedLocales: supportedLocales,
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
        ],
        home: Scaffold(
          appBar: BrnAppBar(
            //自定义左侧icon
            automaticallyImplyLeading: false,
            themeData: BrnAppBarConfig.light(),
            //文本title
            title: '日日记',
          ),
          body: SingleChildScrollView(
            child:
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Container(
                decoration: BoxDecoration(
                  color: const Color.fromARGB(255, 252, 254, 255),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1), // 阴影的颜色
                      offset: const Offset(0, 0), // 阴影与容器的距离
                      blurRadius: 0.5, // 高斯的标准偏差与盒子的形状卷积。
                      spreadRadius: 0.0, // 在应用模糊之前，框应该膨胀的量。
                    ),
                  ],
                ),
                child: TableCalendar(
                  locale: 'zh_CN',
                  firstDay: DateTime.utc(2010, 10, 16),
                  lastDay: DateTime.utc(2030, 3, 14),
                  calendarStyle: const CalendarStyle(
                    todayTextStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Color(0xFFFAFAFA),
                      fontSize: 16.0,
                    ), //
                    selectedTextStyle: TextStyle(
                      color: Color(0xFFFAFAFA),
                      fontSize: 16.0,
                    ),
                    outsideDaysVisible: false,
                  ),
                  focusedDay: _focusedDay,
                  headerStyle: HeaderStyle(
                    titleCentered: true,
                    leftChevronVisible: true,
                    rightChevronVisible: true,
                    formatButtonVisible: false,
                    formatButtonDecoration: BoxDecoration(
                      color: const Color.fromARGB(255, 45, 192, 255),
                      borderRadius: BorderRadius.circular(22.0),
                    ),
                    formatButtonTextStyle: const TextStyle(color: Colors.white),
                    formatButtonShowsNext: true,
                  ),
                  calendarBuilders: CalendarBuilders(
                    markerBuilder: (context, day, events) => events.isNotEmpty
                        ? Container(
                            width: 24,
                            height: 24,
                            alignment: Alignment.center,
                            decoration: const BoxDecoration(
                              color: Colors.lightBlue,
                            ),
                            child: Text(
                              '${events.length}',
                              style: const TextStyle(color: Colors.white),
                            ),
                          )
                        : null,
                    selectedBuilder: (context, date, events) => Container(
                        margin: const EdgeInsets.all(10.0),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Theme.of(context).primaryColor,
                            borderRadius: BorderRadius.circular(8.0)),
                        child: Text(
                          date.day.toString(),
                          style: const TextStyle(color: Colors.white),
                        )),
                    todayBuilder: (context, date, events) => Container(
                        margin: const EdgeInsets.all(10.0),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Colors.blue,
                            borderRadius: BorderRadius.circular(8.0)),
                        child: Text(
                          date.day.toString(),
                          style: const TextStyle(color: Colors.white),
                        )),
                    dowBuilder: (context, day) {
                      if (day.weekday == DateTime.saturday ||
                          day.weekday == DateTime.sunday) {
                        final text = DateFormat.E('zh_CN').format(day);
                        return Center(
                          child: Text(
                            text,
                            style: const TextStyle(color: Colors.red),
                          ),
                        );
                      }
                      return null;
                    },
                  ),
                  calendarFormat: _calendarFormat,
                  selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                  onDaySelected: (selectedDay, focusedDay) {
                    setState(() {
                      _selectedDay = selectedDay;
                      // _selectedEvents = _getEventsForDay(selectedDay);
                      //这里到时候处理
                    });
                    setState(() {
                      _selectedDay = selectedDay;
                      _focusedDay = focusedDay;
                      print("选择是 $_focusedDay $selectedDay");
                      _getEventsForDate(focusedDay);
                    });
                  },
                  //年月日视图选择
                  onFormatChanged: (format) {
                    setState(() {
                      _calendarFormat = format;
                    });
                  },
                  //获取分页起始时间
                  onPageChanged: (focusedDay) {
                    print("111focusedDay ${_focusedDay}");
                    print("focusedDay ${focusedDay}");
                    _focusedDay = focusedDay;
                    _pageChangeDay = focusedDay;
                    _getEventsForDate(focusedDay);
                  },
                ),
              ),
              ListView.separated(
                separatorBuilder: (_, __) => const SizedBox(
                  height: 10,
                ),
                itemCount: _pageChangeEvents.length,
                padding: const EdgeInsets.all(20),
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext ctxt, int index) {
                  var diary = _pageChangeEvents[index];
                  return Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                            flex: 2,
                            child: ListTile(
                              title: Text(
                                '${diary.day}',
                                textAlign: TextAlign.center,
                                style: const TextStyle(fontSize: 22),
                              ),
                              subtitle: Text(
                                '${diary.week}',
                                textAlign: TextAlign.center,
                                style: const TextStyle(fontSize: 12),
                              ),
                            )),
                        Expanded(
                          flex: 11,
                          child: Container(
                            padding: const EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.1), // 阴影的颜色
                                  offset: const Offset(3, 3), // 阴影与容器的距离
                                  blurRadius: 5.0, // 高斯的标准偏差与盒子的形状卷积。
                                  spreadRadius: 0.0, // 在应用模糊之前，框应该膨胀的量。
                                ),
                              ],
                              color: const Color.fromARGB(255, 255, 255, 255),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    GestureDetector(
                                      child: Text(
                                        diary.title ?? '',
                                        style: const TextStyle(fontSize: 16),
                                      ),
                                      onTapUp: (value) {
                                        Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  const DiaryDetail(),
                                              settings: RouteSettings(
                                                  arguments: {
                                                    'diaryId': diary.diaryId
                                                  }) // 需要跳转的页面
                                              ),
                                        ).then((value) {
                                          _getEventsForDate(_focusedDay);
                                        });
                                      },
                                    ),
                                  ],
                                ),
                                Container(
                                  margin: const EdgeInsets.only(bottom: 5),
                                  child: Text(
                                    diary.content ?? '',
                                    style: const TextStyle(
                                        fontSize: 14,
                                        height: 1.5,
                                        color: Color.fromARGB(255, 95, 95, 95)),
                                  ),
                                ),
                                Offstage(
                                    offstage: true,
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Image.asset(
                                          'assets/image/icon_navbar_sousuo_hei.png',
                                          scale: 3.0,
                                          width: 20,
                                          height: 20,
                                        ),
                                        Image.asset(
                                          'assets/image/icon_navbar_sousuo_hei.png',
                                          scale: 3.0,
                                          width: 20,
                                          height: 20,
                                        ),
                                        Image.asset(
                                          'assets/image/icon_navbar_sousuo_hei.png',
                                          scale: 3.0,
                                          width: 20,
                                          height: 20,
                                        ),
                                      ],
                                    )),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Align(
                                      alignment: const Alignment(-0.5, 0),
                                      child: Text(
                                        diary.createTimeSt ?? '13:21 · 晴1',
                                        style: const TextStyle(
                                            fontSize: 13,
                                            color: Color.fromARGB(
                                                255, 180, 180, 180)),
                                      ),
                                    ),
                                    const Align(
                                      alignment: Alignment(0.5, 0),
                                      child: Text(
                                        '',
                                        style: TextStyle(
                                            fontSize: 13,
                                            color: Color.fromARGB(
                                                255, 180, 180, 180)),
                                      ),
                                    ),
                                  ],
                                )
                              ],
                            ),
                          ),
                        ),
                      ]);
                },
              ),
            ]),
          ),
          floatingActionButton: FloatingActionButton(
            heroTag: 'addDiary',
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const DiaryAdd(),
                      settings: RouteSettings(arguments: {
                        "selectedDay": _selectedDay,
                        "dairy": null
                      }) // 需要跳转的页面
                      )).then((value) {
                if (value != null) {
                  _getEventsForDate(_pageChangeDay);
                }
              });
            },
            child: const Icon(Icons.add),
          ),
        ));
  }
}
